package com.xht.job;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xht.constants.SystemConstants;
import com.xht.domain.entity.Article;
import com.xht.mapper.ArticleMapper;
import com.xht.service.ArticleService;
import com.xht.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 文章浏览量定时更新
 */
@Component
public class UpdateViewCountJob {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ArticleMapper articleMapper;

    @Scheduled(cron = "0/59 * * * * ? ")//每1分钟执行一次该方法
    @Transactional
    public void updateViewCount() {
        //获取redis中的浏览量
        Map<String, Integer> viewCountMap = redisCache.getCacheMap(SystemConstants.VIEW_COUNT);

//        List<Article> articles = viewCountMap.entrySet()
//                .stream()
//                .map(entry -> new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue()))
//                .collect(Collectors.toList());
        //更新到数据库中
//        articleService.updateBatchById(articles);

        viewCountMap.forEach((k, v) -> {
            LambdaUpdateWrapper<Article> wrapper = Wrappers.lambdaUpdate(Article.class)
                    .eq(Article::getId, Long.parseLong(k))
                    .set(Article::getViewCount, Long.valueOf(v));
            Article eneity = articleMapper.selectById(Long.valueOf(k));
            articleMapper.update(eneity, wrapper);
        });

        System.out.println("redis数据更新了");
    }
}
